import 'package:dio/dio.dart';
import 'package:html/parser.dart';

class CityInfo {
  String province;
  String city;
  String adcode;
  String rectangle;

  CityInfo({
    required this.province,
    required this.city,
    required this.adcode,
    required this.rectangle,
  });

  @override
  String toString() {
    return 'CityInfo{province: $province, city: $city, adcode: $adcode, latlon: $rectangle}';
  }
}

class IpService {
  static Future<CityInfo> getCityCodeByIpAddress(String ip) async {
    Dio dio = Dio();
    var res = await dio.get(
      'https://restapi.amap.com/v3/ip?ip=$ip&output=json&key=9db1b21c9bc15e7b2f74a7fe616c2914',
    );

    return CityInfo(
      province: res.data['province'],
      city: res.data['city'],
      adcode: res.data['adcode'],
      rectangle: res.data['rectangle'],
    );
  }

  static Future<String> getIpAddress() async {
    Dio dio = Dio();
    var res = await dio.get(
      'https://my-ip.cc/zh-hans/',
      options: Options(
        headers: {
          'User-Agent':
              'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        },
      ),
    );
    var doc = HtmlParser(res.data).parse();
    var t = doc.querySelectorAll('body>.light>div>table>tbody>tr>td')[0].text;
    return t;
  }
}
